//Copyright (C) 2011 Ron Coleman. Contact: ronncoleman@gmail.com
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 3 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

/*
 * LinkSelectDialog.java
 *
 * Created on Jan 8, 2011, 2:58:03 PM
 */

package org.workplicity.cia.ui;

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.workplicity.cia.table.ElogsSummaryTableModel;
import org.workplicity.cia.table.render.ElogsSummaryTableRenderer;
import org.workplicity.cia.util.CIAHelper;
import org.workplicity.cia.util.Pair;
import org.workplicity.elog.entry.Elog;
import org.workplicity.elog.entry.ElogUser;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

/**
 * This class implements the elog link select dialog.
 * @author Ron Coleman
 */
public class LinkSelectDialog extends javax.swing.JDialog {
    public final static String TAG_LINK = "LINK";

    private final ElogUser owner;
    private final ElogUser me = (ElogUser) Helper.whoAmI(WorkletContext.getInstance());

    /** Creates new form LinkSelectDialog */
    public LinkSelectDialog(javax.swing.JDialog parent, ElogUser owner) {
        super(parent, true);
        initComponents();

        this.setTitle("Netlog (" + me.getLogname() + ") >> Edit >> Link");

        this.owner = owner;

        init();
    }

    /**
     * Initialize the dialog.
     */
    private void init() {
        this.ownerTextField.setText(owner+"");

        formatTable();

        ElogsSummaryTableModel model =
                (ElogsSummaryTableModel) this.elogsSummaryTable.getModel();

        loadModelAge(model);
        
        model.setReposName(owner.getReposTitle());

        model.refresh();

        if(model.getRowCount() == 0)
            this.linkButton.setEnabled(false);
    }

    /**
     * Sets up the age filters in the model.
     * @param model Table model
     */
    private void loadModelAge(ElogsSummaryTableModel model) {
        // Populate the age combo box
        this.ageComboBox.removeAllItems();

        for(int i=0; i < CIAHelper.AGES.length; i++)
            this.ageComboBox.addItem(CIAHelper.AGES[i]);

        // Set the age range in the model
        int age = this.ageComboBox.getSelectedIndex();

        String key = CIAHelper.AGES[age];

        HashMap<String,Pair<Long,Long>> map = CIAHelper.getAgeMap();

        Long starts = map.get(key).getStarts();
        Long ends = map.get(key).getEnds();

        model.setStart(starts);
        model.setEnd(ends);
    }

    /**
     * Formats the table for L&F
     */
    private void formatTable() {
        // Position the dial
        this.setLocationRelativeTo(null);

        // The code below left justified the columns
        // but they dont have the L&F of the default
        // settings
//        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
//        renderer.setHorizontalAlignment(SwingConstants.LEFT);
//        elogTable.getColumn(elogTable.getColumnName(1)).setHeaderRenderer(renderer);

        this.elogsSummaryTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        final int[] WIDTHS = {
             40,  // Link state
             75,  // Update date
             75,  // Type
            180   // Description
        };

        for(int i=0; i < WIDTHS.length; i++) {
            TableColumn col = this.elogsSummaryTable.getColumnModel().getColumn(i);

            col.setPreferredWidth(WIDTHS[i]);
        }

        TableColumnModel cm = this.elogsSummaryTable.getColumnModel();

        ElogsSummaryTableRenderer cr = new ElogsSummaryTableRenderer();

        for (int i = 0; i < this.elogsSummaryTable.getColumnCount(); i++) {
            cm.getColumn(i).setCellRenderer(cr);
        }

        // Add mouse support for the request table
        // See http://mycodepage.blogspot.com/2006/09/how-to-create-double-click-event-on.html
        this.elogsSummaryTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    JTable target = (JTable) e.getSource();
                    final int row = target.getSelectedRow();
                    //int column = target.getSelectedColumn();
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            editEntry(row);
                        }
                    });

                }
            }
        });
    }

    private void editEntry(int row) {
        ElogsSummaryTableModel model =
                (ElogsSummaryTableModel) this.elogsSummaryTable.getModel();

        Elog elog = model.getRow(row);

        ElogEditDialog dialog = new ElogEditDialog(this,owner,elog);

        dialog.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        ownerTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        elogsSummaryTable = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        ageComboBox = new javax.swing.JComboBox();
        cancelButton = new javax.swing.JButton();
        linkButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("Owner:");

        ownerTextField.setEditable(false);
        ownerTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        ownerTextField.setText("jTextField1");

        elogsSummaryTable.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        elogsSummaryTable.setModel(new ElogsSummaryTableModel( ));
        jScrollPane1.setViewportView(elogsSummaryTable);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Age:");

        ageComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        ageComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<= 24 hours", "<= 48 hours", "<= 1 week", "<= 30 days", "> 30 & <= 60 days", "> 60  & <= 90 days", "> 90 & <= 180 days", "> 180 & <= 365 days", "> 1 year" }));
        ageComboBox.setSelectedIndex(2);

        cancelButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        linkButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        linkButton.setText("Link");
        linkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                linkButtonActionPerformed(evt);
            }
        });

        refreshButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/refresh2.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ownerTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 182, Short.MAX_VALUE)
                        .addComponent(linkButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(ownerTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(ageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(linkButton, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
                    .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
                    .addComponent(refreshButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void linkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_linkButtonActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            private Component dialog;

            public void run() {
                int row = elogsSummaryTable.getSelectedRow();

                if(row == -1) {
                    JOptionPane.showMessageDialog(dialog, "Select an row to create the link.",
                            "Netlog", JOptionPane.ERROR_MESSAGE);

                    return;
                }

                ElogsSummaryTableModel model =
                        (ElogsSummaryTableModel) elogsSummaryTable.getModel();

                Elog elog = model.getRow(row);

                elog.setReposTitle(owner.getReposTitle());

                WorkletContext context = WorkletContext.getInstance();

                context.publish(TAG_LINK, elog);

                dispose();
            }
        });

    }//GEN-LAST:event_linkButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                LinkSelectDialog dialog = new LinkSelectDialog(null, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox ageComboBox;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTable elogsSummaryTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton linkButton;
    private javax.swing.JTextField ownerTextField;
    private javax.swing.JButton refreshButton;
    // End of variables declaration//GEN-END:variables

}
